<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\rewardOrder;
use App\Models\Demands;
use App\Models\Users;
use App\Models\Mails;
use App\Models\Messages;

use App\Models\OrderDetail;
use App\Models\BalanceLogs;

use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\BidLogExport;
class BidLogController extends Controller {

    /**
     * 页面
     * @return view
     */
    public function index(Request $request){
        $demand_id = (int)$request->get('demand_id',0);
        $demand_title = Demands::where('id',$demand_id)->value('title');
        return view('admin.demand.bid_list',compact('demand_id','demand_title'));
    }

    /**
     * 列表数据
     * @param Request $request
     * @return bool
     */
    public function list(Request $request){
        try{
        	$params = [
        			'status' => (int)$request->get('status',0),
        			'reward_id' => (int)$request->get('demand_id',0)
        	];
        	
        	
        	$lists = rewardOrder::getList($params);
        	foreach($lists as $k=>$v){
        		$lists[$k]['demand'] = Demands::where("id",$v['reward_id'])->first(['id','user_id','user_name','price','start_at','end_at','title']);
        		$lists[$k]['userinfo'] = Users::where("id",$v['user_id'])->first(['id','mobile','reward_num','nickname']);
        	}
        		
        	return $this->writeJson(0,$lists);
        }catch (\Exception $e){
        	return $this->writeJson(1,null,$e->getMessage());
        }
    }
    
    
    /**
     * 编辑
     * @param Request $request
     * @return bool|view
     */
    public function edit(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $info = [];
            if($id){
                $info = rewardOrder::findOrFail($id);
                $info['demand'] = Demands::findOrFail($info['reward_id']);
                $info['detail'] = OrderDetail::where('order_id',$info['id'])->first();
                $info['user_info'] = Users::findOrFail($info['user_id']);
             //   $info['user_info'] = Users::findOrFail($info['user_id']);
            }           
            $info = json_encode($info);
            return view('admin.demand.reward_order_detail',compact('info','id'));
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }
    

    /**
     * 中标
     * @param Request $request
     * @return bool
     */
    public function active(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            
            $order = rewardOrder::where("id",$id)->first(['id','user_id','reward_id','end_time','submit_times','check_status','get_money']);
            $order_id = $order['id'];
            $reward = Demands::where('id',$order['reward_id'])->first();
            
            if(!$order) {
            	return response()->json(["code"=>0, "msg"=>'数据异常']);
            }
             
            if($order['check_status'] >0 ){
            	return response()->json(["code"=>0, "msg"=>'已经审核过了']);
            }

            $check_status = (int)$request->post('status');
            if(!$check_status){
            	return response()->json(["code"=>0, "msg"=>'请选择审核是否通过']);
            }
            
            
            //审核时，已完成数达到任务总数，直接视为失败
            if($reward['ownnumber']>=$reward['number']){

            	$order1['status'] = 4;
            	$order1['check_status'] = 2;
            	$info = rewardOrder::findOrFail($order_id);
            	$info->update($order1);
            	$content = '您接受的任务"' .$reward['title'] .'"审核失败，其它赏金猎人先于您一步完成，请下次加油';
            }else{

            	$order2['status'] = 3;
            	$order2['check_status'] = 1;
            	$info = rewardOrder::findOrFail($order_id);
            	$info->update($order2);
            	//新增余额
            	Users::where('id',$order['user_id'])->increment('balance',$order['get_money']);
            	//成功数+1
            	Demands::where('id',$order['reward_id'])->increment('ownnumber');
            	$content = '您接受的任务"' .$reward['title'] .'"审核通过，赏金增加'.$order['get_money'];
            
            	$user_info = Users::where('id',$order['user_id'])->where('status','<>',-1)->first(['true_name','nickname','inviter_id']);
            	$balance = [
            			'user_id' => $order['user_id'],
            			'user_name' => $user_info['true_name']?$user_info['true_name']:$user_info['nickname'],
            			'money' => $order['get_money'],
            			'balance' => '+'.$order['get_money'],
            				
            			'desc' => '任务收益',
            			'type' => 1,
            	];
            	$balance_info = BalanceLogs::create($balance);
            
            	//查询是否有团长，有的话团长金额增加
            	if($user_info['inviter_id']>0){
            		//有上级，查看是否有返佣资格
            		$my_numbers = Users::where(array("inviter_id"=>$user_info['inviter_id'],"type"=>2,"status"=>2))->count("id");
            		if($my_numbers>=10){
            			$base = Configs::getConfig('base');
            
            			Users::where('id',$user_info['inviter_id'])->increment('balance',$order['get_money']*$base['captain_rate']/100);
            			$msg = '您的团员'.$user_info['nickname'].'完成任务"' .$reward['title'] .'"获得佣金'.$order['get_money']*$base['captain_rate']/100;
            			$template1 = [
            					'title' => '佣金提成通告',
            					'content' => $msg,
            					'user_id' => $user_info['inviter_id'],
            					'status' => 1,
            					'type' => 1
            			];
            			//站内信
            			Mails::create($template1);
            			$inviter = Users::where('id',$user_info['inviter_id'])->where('status','<>',-1)->first(['true_name','nickname','inviter_id']);
            			$balance = [
            					'user_id' => $user_info['inviter_id'],
            					'user_name' => $inviter['true_name']?$inviter['true_name']:$inviter['nickname'],
            					'money' => $order['get_money']*$base['captain_rate']/100,
            					'balance' => '+'.$order['get_money']*$base['captain_rate']/100,
            					'desc' => '团员收益提成',
            					'type' => 1,
            			];
            			$balance_info = BalanceLogs::create($balance);
            		}
            	}
            }
            
             return $this->writeJson(0,'审核成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }
    
    public function lock(Request $request){
    	try{
    		$data = $request->all();
    	
    		$id  = $data['id'];
    		if(empty($id)){
    			return $this->writeJson(1,null,'参数错误');
    		}
    
    		$order = rewardOrder::where("id",$id)->first(['id','user_id','reward_id','end_time','submit_times','check_status','get_money']);
    		$order_id = $order['id'];
    		$reward = Demands::where('id',$order['reward_id'])->first();
    
    		if(!$order) {
    			return response()->json(["code"=>0, "msg"=>'数据异常']);
    		}
    		 
//     		if($order['check_status'] >0 ){
//     			return response()->json(["code"=>0, "msg"=>'已经审核过了']);
//     		}
    
    		
    
    		$order3['status'] = 4;
    		$order3['check_status'] = 2;
    		$order3['staus_end_time']=time()+3600*12;
    		$info = rewardOrder::findOrFail($order_id);
    		$info->update($order3);
    		
    		$content = '您接受的任务"' .$reward['title'] .'"审核不通过，请到任务中心查看详情';
    		
    		
    		$template = [
    				'title' => '任务通告',
    				'content' => $content,
    				'user_id' => $order['user_id'],
    				'status' => 1,
    				'type' => 1
    		];
    		//站内信
    		Mails::create($template);
    
    		
    		
    		$orderdetail = [
    				'step1_remark' =>$data['step1_remark'],
    				'step2_remark' =>$data['step2_remark'],
    				'step3_remark' =>$data['step3_remark'],
    				'step4_remark' =>$data['step4_remark'],
    				'step5_remark' =>$data['step5_remark'],
    				'step6_remark' =>$data['step6_remark'],
    		];
    		OrderDetail::where('order_id',$order_id)->update($orderdetail);
    		
    		return $this->writeJson(0,'操作成功');
    	}catch (\Exception $e){
    		return $this->writeJson(1,null,$e->getMessage());
    	}
    }

    /**
     * 确认已支付，完成订单
     * @param Request $request
     * @return bool
     */
    public function pay(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = BidLists::findOrFail($id);
            $update_arr = [
                'pay_status' =>BidLists::PAY_STATUS_2,
                'pay_time' =>date('Y-m-d H:i:s'),
            ];
            $info->update($update_arr);
            Demands::where('id',$info['demand_id'])->update(['bid'=>4]);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

	 /**
     * Excel导出
     * @param Request $request
     * @return bool
     */
    public function exports(Request $request){
    	$ids = $request->get('ids'); 
    	$export = new BidLogExport($ids);
    	//这里可以传参到服务层
    	return Excel::download($export, '报名列表.xlsx');
    }
    
    
    /**
     * 单个/多个删除
     * @param Request $request
     * @return bool
     */
    public function destroy(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            BidLists::destroy($id);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


}
